package com.appsky.drift.api;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class ServiceConnection {

	private int port = 54250;

	private static ServiceConnection connection = null;

	private Socket serviceSocket = null;

	private InputStream messageIn = null;

	private OutputStream messageOut = null;

	private ServiceConnection(String ip) throws IOException {
		serviceSocket = new Socket(ip, port);
		messageIn = serviceSocket.getInputStream();
		messageOut = serviceSocket.getOutputStream();
		DLog.i("start connection");
	}

	/**
	 * 获取用于与服务器建立连接的connection，里面有messageIn、messageOut等域
	 * 
	 * @return connection
	 * @throws IOException
	 */
	public static ServiceConnection getConnection(String ip) throws IOException {
		if (connection == null) {
			connection = new ServiceConnection(ip);
		}
		return connection;
	}

	/**
	 * 这里应该是sync，但是用了select就况占用阿！
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void sendMessage(String message) throws IOException {
		DLog.i("send content:" + message);
		byte[] messageByteArray = message.getBytes();
		if (messageOut == null) {
			DLog.i("messageOut == null");
		} else {
			DLog.i("messageOut != null");
		}
		messageOut.write(messageByteArray);
		messageOut.flush();
	}

	public synchronized String readMessage() throws SocketTimeoutException,
			IOException {
		return startReadLoop();
	}

	public void setTimeout(int timeout) throws SocketException {
		if (serviceSocket != null && !serviceSocket.isClosed()) {
			serviceSocket.setSoTimeout(timeout);
		}
	}

	public void closeIOAndSocket() {
		closeIOStream();
		closeSocket();
		connection = null;
	}

	public void closeSocket() {
		try {
			if (serviceSocket != null) {
				serviceSocket.close();
				serviceSocket = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void closeIOStream() {
		try {
			if (messageIn != null) {
				messageIn.close();
				messageIn = null;
			}
			if (messageOut != null) {
				messageOut.close();
				messageOut = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String startReadLoop() throws IOException {
		byte[] buff = new byte[1024];
		StringBuffer result = new StringBuffer();
		boolean flag = true;
		String end = null;
		while (flag) {
			DLog.i("开始监听");
			int length = messageIn.read(buff);
			if (length > 0) {
				result.append(new String(buff, 0, length));
				DLog.i("有消息: " + result);
				end = result.substring(result.length() - 3, result.length());
				if (end.equals("END")) {
					flag = false;
					end = result.substring(0, result.length() - 3);
				}
			} else {
				flag = false;
				end = null;
				result = null;
			}
		}
		
		return end;
	}

}
